package com.siao.example.socket;

import java.nio.ByteBuffer;

import com.siao.net.socket.IDataPack;

/**
 * @author Leon
 * 数据包
 */
public class DataPack implements IDataPack {

	/**
	 * 数据类型
	 */
	private int type;

	/**
	 * 数据类型
	 * @return
	 */
	public int getType() {
		return this.type;
	}

	/**
	 * 数据内容
	 */
	private byte[] body;

	/**
	 * 数据内容
	 * @return
	 */
	public byte[] getBody() {
		return this.body;
	}

	/**
	 * 构造函数
	 * @param type
	 * @param body
	 */
	public DataPack(int type, byte[] body) {
		this.type = type;
		this.body = body;
	}

	@Override
	public void write(byte[] bytes) {
		ByteBuffer buffer = ByteBuffer.allocate(this.body.length + bytes.length);
		buffer.put(this.body);
		buffer.put(bytes);
		this.body = buffer.array();
	}

	@Override
	public byte[] read() {
		ByteBuffer buffer = ByteBuffer.allocate(4 + this.body.length);
		buffer.putInt(this.type);
		buffer.put(this.body);
		return buffer.array();
	}

}
